package dev.caobaoqi6040.backend.modules.ai.service.impl;

import dev.caobaoqi6040.backend.modules.ai.service.QwenService;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.ai.chat.memory.ChatMemory;
import org.springframework.core.io.UrlResource;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.net.MalformedURLException;
import java.util.UUID;

/**
 * QwenServiceImpl
 *
 * @author caobaoqi6040
 * @since 2025/10/9 10:53
 */
@Service
public class QwenServiceImpl implements QwenService {

	private final ChatClient client;
	private final String conversationId;

	public QwenServiceImpl(ChatClient qwen) {
		this.client = qwen;
		this.conversationId = UUID.randomUUID().toString();
	}

	@Override
	public String sampleChat(String query) {
		return client.prompt()
			.user(spec -> spec.text(query))
			.advisors(spec -> spec.param(ChatMemory.CONVERSATION_ID, conversationId))
			.call().content();
	}

	@Override
	public String image2SampleText(String url) throws MalformedURLException {
		UrlResource resource = new UrlResource(url);
		return client
			.prompt()
			.user(spec -> spec
				.text("描述图片中的内容")
				.media(MediaType.IMAGE_JPEG, resource))
			.advisors(spec -> spec.param(ChatMemory.CONVERSATION_ID, conversationId))
			.call()
			.content();
	}

	@Override
	public Flux<String> streamChat(String query) {
		return client.prompt()
			.user(spec -> spec.text(query))
			.advisors(spec -> spec.param(ChatMemory.CONVERSATION_ID, conversationId))
			.stream().content();
	}

	@Override
	public Flux<String> image2StreamText(String url) throws MalformedURLException {
		UrlResource resource = new UrlResource(url);
		return client
			.prompt()
			.user(spec -> spec
				.text("描述图片中的内容")
				.media(MediaType.IMAGE_JPEG, resource))
			.advisors(spec -> spec.param(ChatMemory.CONVERSATION_ID, conversationId))
			.stream()
			.content();
	}
}
